package com.raincat.multimediapicker;

import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.raincat.multimediapicker.utils.AlbumHelper;
import com.raincat.multimediapicker.utils.AlbumHelper.onImagesBucketListGetListener;
import com.raincat.multimediapicker.utils.ImageBucket;
import com.raincat.multimediapicker.utils.ImageController;
import com.raincat.multimediapicker.utils.ImageItem;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImageGridFragment extends Fragment {
    private Context context;

    private GridView gridView;
    private TextView tv_preview, tv_original;
    private ImageView iv_original;
    private Button btn_sure;

    private GridAdapter gridAdapter;
    private List<ImageItem> dataList = new ArrayList<>();
    private int imgWidth = 0;
    private int folderIndex = 0;

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = this.getActivity();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.picker_fragment_grid, container, false);
        gridView = (GridView) view.findViewById(R.id.gridview);
        tv_preview = (TextView) view.findViewById(R.id.tv_preview);
        tv_original = (TextView) view.findViewById(R.id.tv_original);
        iv_original = (ImageView) view.findViewById(R.id.iv_original);
        btn_sure = (Button) view.findViewById(R.id.btn_sure);

        if (!ImageController.showOriginalOption) {
            iv_original.setVisibility(View.INVISIBLE);
            tv_original.setVisibility(View.INVISIBLE);
            tv_original.setClickable(false);
        }
        listener();
        return view;
    }

    private void setData() {
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridAdapter = new GridAdapter();
        gridView.setAdapter(gridAdapter);
    }

    private void listener() {
        btn_sure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (ImageController.count != 0) {
                    if (ImageController.Mode == ImageController.TAKE) {
                        finishActivity();
                    } else if (ImageController.Mode == ImageController.CROP) {
                        ((PickerActivity) context).fragmentTabAdapter.addFragment(new ImageCropFragment(), null);
                    }
                }
            }
        });
        tv_original.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                ImageController.isOriginal = !ImageController.isOriginal;
                setOriginal();
            }
        });
        tv_preview.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Bundle bundle = new Bundle();
                bundle.putInt("checkIndex", 0);
                bundle.putInt("folderIndex", -1);
                ((PickerActivity) context).fragmentTabAdapter.addFragment(new ImageVisitFragment(), bundle);
            }
        });
    }

    private void setOriginal() {
        if (iv_original != null) {
            if (!ImageController.isOriginal) {
                iv_original.setImageDrawable(null);
                tv_original.setText(context.getResources().getString(R.string.picker_original));
            } else {
                iv_original.setImageResource(R.drawable.picker_iv_enable);
                tv_original.setText(context.getResources().getString(R.string.picker_original) + ImageController.getImageSize());
            }
        }
    }

    private void setCount() {
        if (btn_sure != null) {
            if (ImageController.count == 0) {
                btn_sure.setBackgroundResource(R.drawable.picker_btn_disable);
                btn_sure.setText(context.getResources().getString(R.string.picker_OK));
            } else {
                btn_sure.setBackgroundResource(R.drawable.picker_btn_enable);
                btn_sure.setText(context.getResources().getString(R.string.picker_OK) + "(" + ImageController.count + "/" + ImageController.maxCount + ")");
            }
            if (ImageController.isOriginal)
                tv_original.setText(context.getResources().getString(R.string.picker_original) + ImageController.getImageSize());
        }
    }

    public void finishActivity() {
        if (ImageController.isOriginal) {
            ImageController.takeRealPathList();
            ((PickerActivity) context).finishActivity("ImageList", ImageController.realPathList);
        } else {
            ImageController.takeZoomPathList(context, new ImageController.OnAllDecodeListener() {
                @Override
                public void onResult() {
                    ((PickerActivity) context).finishActivity("ImageList", ImageController.zoomPathList);
                }
            });
        }
    }

    private class GridAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        GridAdapter() {
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder holder = null;
            if (convertView == null) {
                holder = new Holder();
                convertView = mInflater.inflate(R.layout.picker_fragment_grid_item, parent, false);
                holder.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
                holder.iv_check = (ImageView) convertView.findViewById(R.id.iv_check);
                holder.rl_check = (RelativeLayout) convertView.findViewById(R.id.rl_check);
                holder.tv_error = (TextView) convertView.findViewById(R.id.tv_error);
                holder.tv_suffix = (TextView) convertView.findViewById(R.id.tv_suffix);

                LayoutParams LP = holder.iv_img.getLayoutParams();
                LP.height = imgWidth;
                LP.width = imgWidth;
                holder.iv_img.setLayoutParams(LP);

                convertView.setTag(holder);
            } else
                holder = (Holder) convertView.getTag();

            final ImageItem item = dataList.get(position);
            holder.iv_img.setImageBitmap(null);
            if (item.imageSuffix.equalsIgnoreCase("gif"))
                holder.tv_suffix.setVisibility(View.VISIBLE);
            else
                holder.tv_suffix.setVisibility(View.GONE);

            if (ImageController.imageItemMap.get(item.imagePath) != null) {
                holder.iv_check.setBackgroundResource(R.drawable.picker_check_enable);
                holder.iv_check.setImageResource(R.mipmap.picker_check);
            } else {
                holder.iv_check.setBackgroundResource(R.drawable.picker_check_disable);
                holder.iv_check.setImageDrawable(null);
            }

            holder.rl_check.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    View view = ((RelativeLayout) v).getChildAt(0);
                    if (ImageController.addOrRemoveImageItem(context, item)) {
                        ((ImageView) view).setImageResource(R.mipmap.picker_check);
                        view.setBackgroundResource(R.drawable.picker_check_enable);
                    } else {
                        ((ImageView) view).setImageDrawable(null);
                        view.setBackgroundResource(R.drawable.picker_check_disable);
                    }
                    setCount();
                }
            });

            holder.iv_img.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("checkIndex", position);
                    bundle.putInt("folderIndex", folderIndex);
                    ((PickerActivity) context).fragmentTabAdapter.addFragment(new ImageVisitFragment(), bundle);
                }
            });

            if (item.outHeight == 0 || item.outWidth == 0) {
                holder.iv_img.setVisibility(View.INVISIBLE);
                holder.iv_check.setVisibility(View.INVISIBLE);
                holder.tv_error.setVisibility(View.VISIBLE);
            } else if (item.outHeight == -1 || item.outWidth == -1) {
                try {
                    BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(item.imagePath)));
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeStream(in, null, options);
                    in.close();
                    if (options.outWidth < 1 || options.outHeight < 1) {
                        holder.iv_img.setVisibility(View.INVISIBLE);
                        holder.iv_check.setVisibility(View.INVISIBLE);
                        holder.tv_error.setVisibility(View.VISIBLE);
                    } else {
                        item.outHeight = options.outHeight;
                        item.outWidth = options.outWidth;
                        holder.iv_check.setVisibility(View.VISIBLE);
                        holder.tv_error.setVisibility(View.GONE);
                        Glide.with(context).asBitmap().load(item.imagePath).into(holder.iv_img);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Glide.with(context).asBitmap().load(item.imagePath).into(holder.iv_img);
            }

            ((ViewGroup) convertView).setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            return convertView;
        }

        class Holder {
            public ImageView iv_img, iv_check;
            public TextView tv_error, tv_suffix;
            public RelativeLayout rl_check;
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isAdded() && imgWidth == 0) {
            folderIndex = getArguments().getInt("Index");
            imgWidth = (int) (((PickerActivity) context).getPhoneW() - (25 * ((PickerActivity) context).getScale())) / 4;
            AlbumHelper.getInstance(context).getImagesBucketList(new onImagesBucketListGetListener() {
                @Override
                public void onFinish(List<ImageBucket> bucketList) {
                    dataList = bucketList.get(folderIndex).imageList;
                    ((Activity) context).runOnUiThread(new Runnable() {
                        public void run() {
                            setData();
                        }
                    });
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        setOriginal();
        setCount();
        if (gridAdapter != null)
            gridAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}
